<template>
  <AppNavbar :fetchProductData="fetchProductData"/>
  <div class="product-info">
    <!-- Product Image -->
    <!--<img :src="product.wareImg" :alt="product.name" class="product-image">-->

    <!-- Product Title -->
    <p>{{ t('name') }}: {{ product.wareName }}</p>

    <!-- Product Price -->
    <p>{{ t('price') }}: {{ product.warePrice }}</p>

    <!-- Product Stock -->
    <p>{{ t('stock') }}: {{ product.stock }}</p>

    <!-- Product Description -->
    <p>{{ t('description') }}: </p>
    <p v-html="renderDescription(product.wareDesc)" class="product-description"></p>

  </div>
</template>

<script>
  import {ref, inject} from 'vue';
  import axios from 'axios';
  import AppNavbar from '@/components/AppNavbar.vue';
  import {useRoute} from 'vue-router';

  export default {
    components: {
      AppNavbar
    },
    setup() {
      // Inject current locale and translation function
      const currentLocale = inject('locale');
      const i18nMessages = {
        'en': {
          name: 'Name',
          description: 'Detail',
          stock: 'Stock',
          image: 'Image',
          price: 'Price',
        },
        'zh-CN': {
          name: '产品名称',
          description: '详细信息',
          stock: '库存',
          image: '图片',
          price: '价格',
        },
      };
      const t = (key) => {
        console.log("key:", key, currentLocale.value)
        return i18nMessages[currentLocale.value][key] || key;
      };
      // Define reactive references for product data and additional images
      const product = ref({
        wareName: '',
        warePrice: 0,
        stock: 0,
        description: '',
        wareImg: ''
      });
      const productImages = ref([]);

      const route = useRoute();
      // Fetch product details and additional images from API
      const fetchProductData = async () => {
        try {
          const response = await axios.get(process.env.VUE_APP_DOMAIN_URL +
              '/ylwares/ylWares/queryById', {
            params: {
              wareId: route.params.wareId, // 传递 wareId 参数
              lan: currentLocale.value
            }
          });
          console.log("Response data:", response.data);


          if (response.data) {
            const {wareName, warePrice, stock, wareDesc, wareImg, wareNameEn, wareDescEn} = response.data.result;
            // 根据当前语言选择性地读取不同字段
            const productName = currentLocale.value === 'en' ? wareNameEn : wareName;
            const productDesc = currentLocale.value === 'en' ? wareDescEn : wareDesc;
            product.value = {
              wareName: productName,
              warePrice,
              stock,
              wareDesc: productDesc,
              wareImg
            };
          }
        } catch (error) {
          console.error('Error fetching product data:', error);
        }
      };

      // Define renderDescription method
      const renderDescription = (description) => {
        if (!description) {
          return ''; // 如果 description 为 undefined 或 null，则返回空字符串
        }
        // 正则表达式用于匹配图片链接
        const imgRegex = /(?:https?|ftp):\/\/[\S]+\.(?:jpg|jpeg|png|gif|bmp)(?:\?[\S]*)?/gi;

        // 将图片链接替换为 <img> 标签
        const descriptionWithImages = description.replace(imgRegex, (imgUrl) => {
          return `<img src="${imgUrl}" alt="Product Image">`;
        });

        // 返回包含图片链接替换后的HTML字符串
        return descriptionWithImages;
      };


      // Call the fetchProductData function when component is mounted
      fetchProductData();

      return {product, productImages, t, fetchProductData, renderDescription};
    }
  };
</script>

<style scoped>
  .product-info {
    display: flex;
    flex-direction: column;
    /*align-items: center; !* 图片居中 *!*/
    /*text-align: center;*/ /* 这里注释掉文本居中样式 */
    background-color: #e6f0fa;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    margin: 20px auto;
    width: 100%;
  }

  .product-info p {
    margin: 20px 0;
    font-size: 18px;
    color: #333;
    max-width: 80%;
    text-align: left; /* 文本左对齐 */
  }

  .product-info img {
    max-width: 80%;
    max-height: 60%;
    width: auto; /* 自动调整宽度 */
    height: 700px;
    object-fit: cover;
    border-radius: 8px;
    margin-bottom: 20px;
    align-items: center;
  }

  .product-description img {
    max-width: 100%; /* 设置图片宽度为容器的100% */
    height: auto; /* 自适应高度 */
    margin-bottom: 10px; /* 图片下方留出一些空间 */
  }
</style>
